package cn.xawl.interview.thread;

import java.util.concurrent.TimeUnit;

/**
 * @author lh
 * @date 2020/08/28 16:07:08
 *
 * Java死锁案例
 *
 * 使用jps查看Java运行程序的pid
 * jstack <pid> 查看进程信息
 *
 **/
public class DeadLockDemo {

    public static void main(String[] args) {

        DeadData data1 = new DeadData("AAA");
        DeadData data2 = new DeadData("BBB");

        new Thread(() -> {
            synchronized (data1) {
                try {
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "\t获取到" + data1 + "尝试获取" + data2);
                synchronized (data2) {
                    System.out.println(Thread.currentThread().getName() + "\t获取到" + data2);
                }
            }
        }, "A").start();
        new Thread(() -> {
            synchronized (data2) {
                try {
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "\t获取到" + data2 + "尝试获取" + data1);
                synchronized (data1) {
                    System.out.println(Thread.currentThread().getName() + "\t获取到" + data1);
                }
            }
        }, "B").start();
    }

}

class DeadData {
    String data;

    public DeadData(String data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "DeadData{" +
                "data='" + data + '\'' +
                '}';
    }
}
